package com.micro.controller;

import com.micro.model.Know;
import com.micro.model.KnowLib;
import com.micro.model.Subject;
import com.micro.model.User;
import com.micro.service.KnowLibService;
import com.micro.service.SubjectService;
import com.micro.service.UserService;
import com.micro.util.*;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/subject")
public class SubjectController {
	@Autowired
	private Know know;

	static Logger log4j = Logger.getLogger(SubjectController.class.getClass());
	private ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:conf/spring.xml"
			,"classpath:conf/spring-mybatis.xml"});

	@RequestMapping("qryInitData.do") //"value="qryInitData.do",method=RequestMethod.POST
	public void qryInitData(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		SubjectService subjectService = (SubjectService) context.getBean("subjectServiceImpl");
		String condition = request.getParameter("condition").toString();
		String subjectCatName = request.getParameter("subjectCatName").toString();

		Subject conditionBean = new Subject();
		if (!"all".equals(condition)) {
			conditionBean.setSubjectTitle(condition);
			conditionBean.setSubjectContent(condition);
		} else {
			conditionBean.setSubjectCatName(subjectCatName);
		}
		List<Subject> subjectList = subjectService.querySubjectList(conditionBean);
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonString = objectMapper.writeValueAsString(subjectList);
		response.getWriter().write(jsonString);
	}

	/**
	 * 查询无目录文档
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("qryInitDataByCond.do")
	public void querySubjectListByCond(HttpServletRequest request, HttpServletResponse response) throws IOException {
		SubjectService subjectService = (SubjectService) context.getBean("subjectServiceImpl");
		String pSubjectId = request.getParameter("pSubjectId").toString();
		String knowCode = request.getParameter("knowCode");

		Subject conditionBean = new Subject();
		conditionBean.setpSubjectId(pSubjectId);
		conditionBean.setSubjectCatName(knowCode);

		List<Subject> subjectList = subjectService.querySubjectListByCond(conditionBean);
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonString = objectMapper.writeValueAsString(subjectList);
		response.getWriter().write(jsonString);
	}


	@RequestMapping("qrySubjectById.do") //"value="qryInitData.do",method=RequestMethod.POST
	public void qrySubjectById(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		SubjectService subjectService = (SubjectService) context.getBean("subjectServiceImpl");
		Subject subject = new Subject();
		subject.setSubjectId(request.getParameter("subjectId").toString());
		Subject subjectResult = subjectService.querySubjectListByID(subject);

		// 查询，后移除缓存
		// CacheManager.remove(subject.getSubjectId());

		ObjectMapper objectMapper = new ObjectMapper();
		String jsonString = "";
		jsonString = objectMapper.writeValueAsString(subjectResult);
		response.getWriter().write(jsonString);
	}

	/**
	 * 打开编辑操作获取缓存
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 */
	@RequestMapping("getCache.do")
	public void getCache(HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
		ObjectMapper objectMapper = new ObjectMapper();
		String subjectId = request.getParameter("subjectId").toString();

		// 是否清除缓存
//		String flag = request.getParameter("flag").toString();
		if (null != subjectId) {
			String jsonString = "false";
			String subjectIdCache = (String)CacheManager.get(subjectId);
			User user = new User();
			if (null != subjectIdCache) {
				user.setUserName(URLDecoder.decode(subjectIdCache, "utf-8"));
			}
			if (StringUtil.isBlank(subjectIdCache)) {
				// 无缓存，可以编辑
				jsonString = objectMapper.writeValueAsString(false);
			} else {
				// 有缓存，不可以编辑
				jsonString = objectMapper.writeValueAsString(user);
			}
			response.getWriter().write(jsonString);
		}
	}

	/**
	 * 确认开启编辑设置缓存
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 */
	@RequestMapping("setCache.do")
	public void setCache(HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
		ObjectMapper objectMapper = new ObjectMapper();
		String subjectId = request.getParameter("subjectId").toString();
		String userName = request.getParameter("userName").toString();

		// 是否清除缓存
		String flag = request.getParameter("flag").toString();
		if (null != subjectId) {
			if ("Y".equals(flag)) {
				CacheManager.remove(subjectId);
			} else {
				CacheManager.put(subjectId,URLEncoder.encode(userName, "utf-8"),5,TimeUnit.MINUTES);
			}

			String jsonString = objectMapper.writeValueAsString(true);
			response.getWriter().write(jsonString);
		}
	}

	/**
	 * 匿名发布主题
	 * @param subject
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 */
	@RequestMapping("insertAnonymouSubject.do") //"value="qryInitData.do",method=RequestMethod.POST
	public ModelAndView insertAnonymouSubject(Subject subject) throws IOException, NoSuchAlgorithmException {

		ModelAndView mv = new ModelAndView("redirect:/modules/micro/html/micro.jsp");
		SubjectService subjectService = (SubjectService) context.getBean("subjectServiceImpl");

		KnowLibService knowLibService = (KnowLibService) context.getBean("knowLibServiceImpl");
		List<KnowLib> knowLibList = knowLibService.queryKnowLibList();

		subject.setSubjectId(UUIDTool.getUUID());
		subject.setpSubjectId(subject.getpSubjectId());

		if(null != subject.getSubjectContent() && !"".equals(subject.getSubjectContent())) {
			String newContent = subject.getSubjectContent().replaceAll("<a href", "<a target=\"_blank\" href");
			newContent = subject.getSubjectContent().replaceAll("<a target=\"_self\"", "<a target=\"_blank\"");
			newContent = subject.getSubjectContent().replaceAll("target=\"_self\"", "target=\"_blank\"");
			subject.setSubjectContent(newContent);
			subject.setSubjectContentByte(subject.getSubjectContent().getBytes("UTF-8"));
		}

//		subject.setSubjectCatName("交管产品长研知识库");
		subject.setSubjectTop("0");
		subject.setSubjectLaud(0);

		int result = 0;//subjectService.querySubjectIsExistByTitle(subject.getSubjectTitle());
		if(result == 0) {
			result = subjectService.insertSubject(subject);
			if(result == 0) {
				DingMessageUtil.sendToDingDing(subject,subject.getSubjectTitle(),"[哇， "+subject.getUserName()+" 发布了新文档：" + subject.getSubjectTitle() + " ，快来围观!](" + know.getSysUrl() + subject.getSubjectId()+")", knowLibList);

				//mv.addObject("message", "YES");
				log4j.info("插入主题成功!    subjectId = " + subject.getSubjectId());
			} else {
				//mv.addObject("message","NO");
				log4j.info("主题已存在，无需重复插入。!    subjectId = " + subject.getSubjectId());
			}
		}

		return  mv;
	}

	/**
	 * 匿名回复主题
	 * @param subject
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 */
	@RequestMapping("insertReplySubject.do") //"value="qryInitData.do",method=RequestMethod.POST
	public ModelAndView insertReplySubject(Subject subject) throws IOException, NoSuchAlgorithmException {
		ModelAndView mv = new ModelAndView("redirect:/modules/micro/html/micro.jsp");
		SubjectService subjectService = (SubjectService) context.getBean("subjectServiceImpl");

		KnowLibService knowLibService = (KnowLibService) context.getBean("knowLibServiceImpl");
		List<KnowLib> knowLibList = knowLibService.queryKnowLibList();

		if ("edit".equals(subject.getFlag())) {
			subject.setSubjectId(subject.getSubjectId());
			if(null != subject.getSubjectContent() && !"".equals(subject.getSubjectContent())) {
				String newContent = subject.getSubjectContent().replaceAll("<a href", "<a target=\"_blank\" href");
				newContent = subject.getSubjectContent().replaceAll("<a target=\"_self\"", "<a target=\"_blank\"");
				newContent = subject.getSubjectContent().replaceAll("target=\"_self\"", "target=\"_blank\"");
				subject.setSubjectContent(newContent);
				subject.setSubjectContentByte(subject.getSubjectContent().getBytes("UTF-8"));
			}

//			subject.setSubjectCatName("交管产品长研知识库");
			subject.setSubjectTop("0");
			subject.setSubjectLaud(0);

			int result = subjectService.editSubject(subject);
			subject = subjectService.querySubjectListByID(subject);
			if(result == 0) {
				DingMessageUtil.sendToDingDing(subject,subject.getSubjectTitle(),"[哇，文档：" + subject.getSubjectTitle() + " 被 "+subject.getModifyUserName()+" 更新了，快来关注!](" + know.getSysUrl() + subject.getSubjectId()+")", knowLibList);
				// 修改成功后移除缓存
				CacheManager.remove(subject.getSubjectId());

				//mv.addObject("message", "YES");
				log4j.info("成功回复主题!   subjectId = " + subject.getSubjectId());
			} else {
				//mv.addObject("message","NO");
				log4j.info("回复失败!     subjectId = " + subject.getSubjectId());
			}
		} else {
			subject.setSubjectId(UUIDTool.getUUID());
			if(null != subject.getSubjectContent() && !"".equals(subject.getSubjectContent())) {
				String newContent = subject.getSubjectContent().replaceAll("<a href", "<a target=\"_blank\" href");
				newContent = subject.getSubjectContent().replaceAll("<a target=\"_self\"", "<a target=\"_blank\"");
				newContent = subject.getSubjectContent().replaceAll("target=\"_self\"", "target=\"_blank\"");
				subject.setSubjectContent(newContent);
				subject.setSubjectContentByte(subject.getSubjectContent().getBytes("UTF-8"));
			}

//			subject.setSubjectCatName("交管产品长研知识库");
			subject.setSubjectTop("0");
			subject.setSubjectLaud(0);

			int result = subjectService.insertSubject(subject);
			if(result == 0) {
				DingMessageUtil.sendToDingDing(subject,subject.getSubjectTitle(),"[哇， "+subject.getUserName()+" 发布了新文档：" + subject.getSubjectTitle() + " ，快来看看!](" + know.getSysUrl() + subject.getSubjectId()+")", knowLibList);

				//mv.addObject("message", "YES");
				log4j.info("成功回复主题!   subjectId = " + subject.getSubjectId());
			} else {
				//mv.addObject("message","NO");
				log4j.info("回复失败!     subjectId = " + subject.getSubjectId());
			}
		}

		return mv;
	}
	@RequestMapping("insertSubject.do") //"value="qryInitData.do",method=RequestMethod.POST
	public void insertSubject(HttpServletRequest request, HttpServletResponse response, Subject subjectObj) throws IOException, NoSuchAlgorithmException {
		SubjectService subjectService = (SubjectService) context.getBean("subjectServiceImpl");
		UserService userService = (UserService) context.getBean("userServiceImpl");

		String pubFlag = "";
		String oprateFlag = "";

		// 如果实名发布，实名回复

		// 如果实名发布 实名回复 用户与密码 联合查询 不存在在创建用户
		User user = new User();
		user.setUserName(request.getParameter("USER_NAME"));
		user.setUserPwd(Md5Util.EncoderByMd5(request.getParameter("USER_PWD").toString()));
		User resultUser = userService.queryUserByNameAndPwd(user);
		if("0".equals(resultUser.getUserId())) {
			// 添加用户
			User newUser = new User();
			newUser.setUserId(UUIDTool.getUUID());
			newUser.setUserName(request.getParameter("USER_NAME"));
			newUser.setUserPwd(Md5Util.EncoderByMd5(request.getParameter("USER_PWD")));

			userService.insertUser(user);
		}

		// 如果匿名发布，匿名回复 不需要走用户检测

		// 发布主题
		Subject subject = new Subject();
		subject.setSubjectId(UUIDTool.getUUID());
		// 如果发布 pSubjectId = -1 否则 平SubjectId = subjectId
		subject.setpSubjectId("-1");
		subject.setSubjectTitle(request.getParameter("SUBJECT_TITLE"));
		subject.setSubjectContent(request.getParameter("SUBJECT_CONTENT"));
		subject.setSubjectContentByte(subject.getSubjectContent().getBytes("UTF-8"));
		subject.setSubjectCatName(request.getParameter("SUBJECT_CAT_NAME"));
		subject.setUserName(request.getParameter("USER_NAME"));
		subject.setSubjectTop("0");
		subject.setSubjectLaud(0);

		int result = subjectService.insertSubject(subject);

		if(result == 1) {
			response.getWriter().write("YES");
		} else {
			response.getWriter().write("NO");
		}
	}
}
